package OSMS.action.goodsfunc;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import OSMS.dao.GoodsDao;
import OSMS.entity.Customers;
import OSMS.entity.Order;
/*
 * 订单显示页面
 * 	业务逻辑如下：
 * 1、当用户在商城主页面时点击我的订单时，此时不能通过orderServelet.java来进入orderPage.jsp
 * 2、因为此时除了计算订单总金额外，不能进行任何操作，只能去查看订单。
 * 3、所以写了本文件，获取用户编号cid后直接调用dao里的orderList方法查找对应用户的订单表
 * 		此处获取cid只能获取全局变量中的cid而不能从购物车获取因为此时可能还没有购物车信息
 * 4、然后重定向到orderPage.jsp订单页面进行展示对应用户订单信息。
 * 	
 */
public class showOrderServlet extends HttpServlet {
	private GoodsDao dao = new GoodsDao();
	//计算总金额方法
	public double sum_cost(int cid){
		List<Order> orderList = new ArrayList<Order>();
		try {
			orderList = (ArrayList<Order>)dao.orderList(cid);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		double sum = 0;
		for(int i = 0;i<orderList.size();i++)
		{
			sum+= orderList.get(i).getGood_num()*orderList.get(i).getGprice();
		}
		return sum;
	}
	
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			HttpSession session = request.getSession();
			Object obj_c = session.getAttribute("cus");
			Customers cus = (Customers)obj_c;
//			ArrayList<Car> carList = (ArrayList<Car>)obj_c;
			int cid = cus.getCid();
			//此处为测试：直接赋值
//			int cid = 1;
			// 1. 调用OrderDao的方法查询order数据
			List<Order> orderList = dao.orderList(cid);
			System.out.println(cid);
			
			//计算订单中商品总价值
			double sum_cost = this.sum_cost(cid);
			session.setAttribute("sum_cost", sum_cost);
			System.out.println(sum_cost);
			
			//测试所用输出
			if(orderList.isEmpty()){
				 System.out.println("空的！！！");
			}
			//测试所用输出
	        System.out.println(orderList.toString());
			// 2. 将orderList数据装入域对象中。
			session.setAttribute("orderList", orderList);
			// 3. 选择对应的跳转方式（请求转发）跳转到orderPage.jsp订单结算页面.
			request.setCharacterEncoding("utf-8");
//			request.getRequestDispatcher("orderPage.jsp").forward(request, response);
			response.sendRedirect(request.getServletContext().getContextPath() + "/jsp/goods/orderPage.jsp");
		} catch(Exception ex) {
			ex.printStackTrace();
		}
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doGet(request, response);
	}
	
}
